﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace PS.Engine.Helper
{
    internal static class SerializationHelper
    {
        internal static string GetSerializedXml(object objectToSerialize)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(objectToSerialize.GetType());

            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, objectToSerialize);
                stream.Position = 0;
                xmlDocument.Load(stream);

                return xmlDocument.InnerXml;
            }
        }

        internal static string LoadXml(string path)
        {
            using (StreamReader reader = new StreamReader(path))
            {
                return reader.ReadToEnd();
            }
        }

        internal static void WriteToFile(string content, string path)
        {
            using (StreamWriter writer = new StreamWriter(path))
            {
                writer.Write(content);
            }
        }

        internal static object DeserializeXml(string serializedXml, Type type)
        {
            using (StringReader stringReader = new StringReader(serializedXml))
            using (XmlReader xmlReader = new XmlTextReader(stringReader))
            {
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(xmlReader);
            }
        }
    }
}
